package goods

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gozero-demo/internal/repo/mysql"
	"gozero-demo/internal/svc"
	"gozero-demo/internal/types"
)

type GoodsListLogic struct {
	logx.Logger
	ctx       context.Context
	svcCtx    *svc.ServiceContext
	goodsRepo *mysql.GoodsRepo
}

// 商品列表
func NewGoodsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsListLogic {
	return &GoodsListLogic{
		Logger:    logx.WithContext(ctx),
		ctx:       ctx,
		svcCtx:    svcCtx,
		goodsRepo: mysql.NewGoodsRepo(ctx, svcCtx),
	}
}

func (l *GoodsListLogic) GoodsList(req *types.GoodsListRequest) (resp *types.CommonResponse, err error) {
	//查询数据库
	list, count, err := l.goodsRepo.GetGoodsList(req)
	if err != nil {
		return nil, err
	}

	//组装返回的结构
	respList := make([]types.GoodsListResponseData, 0)
	respData := &types.CommonPageListResp{
		Page:     req.Page,
		PageSize: req.PageSize,
		Total:    count,
		List:     respList,
	}
	if count == 0 {
		return types.SuccessResponse(respData, l.ctx), nil
	}

	//格式化处理返回给前端的结构
	for _, item := range list {
		respList = append(respList, types.GoodsListResponseData{
			GoodsEditRequest: types.GoodsEditRequest{
				Id:             item.ID,
				GoodsName:      item.GoodsName,
				GoodsAttribute: item.GoodsAttribute,
				GoodsCategory:  item.GoodsCategory,
				OriginPlace:    item.OriginPlace,
				Stock:          item.Stock,
				CostPrice:      float64(item.CostPrice) / 100,
				SellingPrice:   float64(item.SellingPrice) / 100,
				Status:         item.Status,
			},
			CreateTime: item.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime: item.UpdateTime.Format("2006-01-02 15:04:05"),
		})
	}
	respData.List = respList
	return types.SuccessResponse(respData, l.ctx), nil
}
